package com.fj.netty.chat.handler;

import com.fj.netty.chat.message.GroupChatResponseMessage;
import com.fj.netty.chat.message.GroupCreateRequestMessage;
import com.fj.netty.chat.pojo.GroupChat;
import com.fj.netty.chat.server.service.GroupSession;
import com.fj.netty.chat.server.service.ServiceFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;

/**
 * @author fj
 * @date 2024/1/12 15:06
 */
@Slf4j
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        GroupSession groupSession = ServiceFactory.getGroupSession();
        GroupChat groupChat = groupSession.create(msg.getUsername(), msg.getGroupName(), msg.getMembers());
        for (String memberName:groupSession.members(groupChat.getName())){
            Channel channel = ServiceFactory.getSession().getChannel(memberName);
            if (channel == null){
                continue;
            }
            if (memberName.equals(groupChat.getCreator())){
                GroupChatResponseMessage groupChatResponseMessage = new GroupChatResponseMessage();
                groupChatResponseMessage.setFrom("系统消息");
                groupChatResponseMessage.setContent("群聊创建成功");
                channel.writeAndFlush(groupChatResponseMessage);
            }else{
                GroupChatResponseMessage groupChatResponseMessage = new GroupChatResponseMessage();
                groupChatResponseMessage.setFrom("系统消息");
                groupChatResponseMessage.setContent("您被加入群聊："+groupChat.getName());
                channel.writeAndFlush(groupChatResponseMessage);
            }
        }
    }
}
